const express = require('express');
const router = express.Router();
const { Order, User } = require('../database/models');
const { 
  authenticate,
  authorize,
  asyncHandler 
} = require('../middleware');
const { 
  validate,
  createOrderValidation,
  updateOrderStatusValidation,
  assignOrderValidation,
  evaluateOrderValidation,
  paginationValidation,
  objectIdValidation
} = require('../middleware/validation');

// 获取工单列表
router.get('/', 
  authenticate,
  validate(paginationValidation, 'query'),
  asyncHandler(async (req, res) => {
    const { page = 1, pageSize = 20 } = req.query;
    const { userId, maintainerId, status, type, urgency } = req.query;
    const currentUser = req.user;

    // 构建查询条件
    const query = {};

    // 根据用户角色限制查询范围
    if (currentUser.role === 'user') {
      query.userId = currentUser._id;
    } else if (currentUser.role === 'maintainer') {
      // 维修员可以看到分配给自己的工单
      query.maintainerId = currentUser._id;
    }
    // 管理员可以看到所有工单

    // 添加过滤条件
    if (userId && currentUser.role === 'admin') {
      query.userId = userId;
    }
    if (maintainerId && currentUser.role === 'admin') {
      query.maintainerId = maintainerId;
    }
    if (status) {
      query.status = status;
    }
    if (type) {
      query.type = type;
    }
    if (urgency) {
      query.urgency = urgency;
    }

    // 计算分页 - 确保类型转换
    const pageNum = parseInt(page);
    const pageSizeNum = parseInt(pageSize);
    const skip = (pageNum - 1) * pageSizeNum;

    // 查询工单
    const [orders, total] = await Promise.all([
      Order.find(query)
        .populate('userId', 'name phone')
        .populate('maintainerId', 'name phone')
        .sort({ createdAt: -1 })
        .skip(skip)
        .limit(pageSizeNum),
      Order.countDocuments(query)
    ]);

    const totalPages = Math.ceil(total / pageSizeNum);

    res.status(200).json({
      success: true,
      message: '获取工单列表成功',
      code: 200,
      data: {
        data: orders,
        total,
        page: pageNum,
        pageSize: pageSizeNum,
        totalPages
      }
    });
  })
);

// 根据ID获取单个工单
router.get('/:orderId', 
  authenticate,
  asyncHandler(async (req, res) => {
    const { orderId } = req.params;
    const currentUser = req.user;

    // 验证ObjectId格式
    if (!orderId.match(/^[0-9a-fA-F]{24}$/)) {
      return res.status(400).json({
        success: false,
        message: '工单ID格式无效',
        code: 400,
        data: null
      });
    }

    const order = await Order.findById(orderId)
      .populate('userId', 'name phone email')
      .populate('maintainerId', 'name phone email specialties rating');

    if (!order) {
      return res.status(404).json({
        success: false,
        message: '工单不存在',
        code: 404,
        data: null
      });
    }

    // 权限检查
    const canView = 
      currentUser.role === 'admin' ||
      order.userId.toString() === currentUser._id.toString() ||
      (order.maintainerId && order.maintainerId._id.toString() === currentUser._id.toString());

    if (!canView) {
      return res.status(403).json({
        success: false,
        message: '没有权限查看此工单',
        code: 403,
        data: null
      });
    }

    res.status(200).json({
      success: true,
      message: '获取工单详情成功',
      code: 200,
      data: order
    });
  })
);

// 创建新工单
router.post('/', 
  authenticate,
  validate(createOrderValidation),
  asyncHandler(async (req, res) => {
    const { title, description, type, urgency, userAddress, images, documents } = req.body;
    const currentUser = req.user;

    // 只有用户可以创建工单
    if (currentUser.role !== 'user') {
      return res.status(403).json({
        success: false,
        message: '只有用户可以创建工单',
        code: 403,
        data: null
      });
    }

    const order = new Order({
      title,
      description,
      type,
      urgency: urgency || 'medium',
      userId: currentUser._id,
      userName: currentUser.name,
      userPhone: currentUser.phone,
      userAddress,
      images: images || [],
      documents: documents || []
    });

    await order.save();

    // 填充关联信息
    await order.populate('userId', 'name phone email');

    res.status(201).json({
      success: true,
      message: '工单创建成功',
      code: 201,
      data: order
    });
  })
);

// 更新工单状态
router.put('/:orderId/status', 
  authenticate,
  validate(updateOrderStatusValidation),
  asyncHandler(async (req, res) => {
    const { orderId } = req.params;
    const { status, notes, serviceFee, serviceDescription } = req.body;
    const currentUser = req.user;

    const order = await Order.findById(orderId);
    if (!order) {
      return res.status(404).json({
        success: false,
        message: '工单不存在',
        code: 404,
        data: null
      });
    }

    // 权限检查
    const canUpdate = 
      currentUser.role === 'admin' ||
      (currentUser.role === 'maintainer' && order.maintainerId && order.maintainerId.toString() === currentUser._id.toString()) ||
      (currentUser.role === 'user' && order.userId.toString() === currentUser._id.toString() && ['cancelled'].includes(status));

    if (!canUpdate) {
      return res.status(403).json({
        success: false,
        message: '没有权限更新此工单状态',
        code: 403,
        data: null
      });
    }

    // 状态转换验证
    const validTransitions = {
      'waiting': ['processing', 'cancelled'],
      'processing': ['waitingPayment', 'completed', 'cancelled'],
      'waitingPayment': ['completed', 'cancelled'],
      'completed': ['evaluating'],
      'cancelled': [],
      'evaluating': ['evaluated'],
      'evaluated': []
    };

    if (!validTransitions[order.status].includes(status)) {
      return res.status(400).json({
        success: false,
        message: `无法从状态 ${order.status} 转换到 ${status}`,
        code: 400,
        data: null
      });
    }

    // 更新工单
    order.status = status;
    if (notes) order.notes = notes;
    if (serviceFee !== undefined) order.serviceFee = serviceFee;
    if (serviceDescription) order.serviceDescription = serviceDescription;

    // 根据角色设置备注
    if (currentUser.role === 'admin' && notes) {
      order.adminNotes = notes;
    }

    await order.save();
    await order.populate(['userId', 'maintainerId']);

    res.status(200).json({
      success: true,
      message: '工单状态更新成功',
      code: 200,
      data: order
    });
  })
);

// 派发工单
router.put('/:orderId/assign', 
  authenticate,
  authorize('admin'),
  validate(assignOrderValidation),
  asyncHandler(async (req, res) => {
    const { orderId } = req.params;
    const { maintainerId, notes } = req.body;

    const [order, maintainer] = await Promise.all([
      Order.findById(orderId),
      User.findById(maintainerId)
    ]);

    if (!order) {
      return res.status(404).json({
        success: false,
        message: '工单不存在',
        code: 404,
        data: null
      });
    }

    if (!maintainer || maintainer.role !== 'maintainer') {
      return res.status(404).json({
        success: false,
        message: '维修员不存在',
        code: 404,
        data: null
      });
    }

    if (!maintainer.isActive) {
      return res.status(400).json({
        success: false,
        message: '该维修员账户已被禁用',
        code: 400,
        data: null
      });
    }

    if (order.status !== 'waiting') {
      return res.status(400).json({
        success: false,
        message: '只能派发等待中的工单',
        code: 400,
        data: null
      });
    }

    // 更新工单
    order.maintainerId = maintainerId;
    order.maintainerName = maintainer.name;
    order.maintainerPhone = maintainer.phone;
    order.status = 'processing';
    order.assignedAt = new Date();
    if (notes) order.adminNotes = notes;

    await order.save();
    await order.populate(['userId', 'maintainerId']);

    res.status(200).json({
      success: true,
      message: '工单派发成功',
      code: 200,
      data: order
    });
  })
);

// 评价工单
router.put('/:orderId/evaluate', 
  authenticate,
  validate(evaluateOrderValidation),
  asyncHandler(async (req, res) => {
    const { orderId } = req.params;
    const { rating, feedback } = req.body;
    const currentUser = req.user;

    const order = await Order.findById(orderId);
    if (!order) {
      return res.status(404).json({
        success: false,
        message: '工单不存在',
        code: 404,
        data: null
      });
    }

    // 只有工单的用户可以评价
    if (order.userId.toString() !== currentUser._id.toString()) {
      return res.status(403).json({
        success: false,
        message: '只能评价自己的工单',
        code: 403,
        data: null
      });
    }

    if (order.status !== 'evaluating') {
      return res.status(400).json({
        success: false,
        message: '工单状态不允许评价',
        code: 400,
        data: null
      });
    }

    // 更新工单评价
    order.rating = rating;
    order.feedback = feedback || '';
    order.status = 'evaluated';

    await order.save();

    // 更新维修员的评分和完成订单数
    if (order.maintainerId) {
      const maintainer = await User.findById(order.maintainerId);
      if (maintainer) {
        const completedCount = maintainer.completedOrders + 1;
        const newRating = ((maintainer.rating * maintainer.completedOrders) + rating) / completedCount;
        
        maintainer.rating = Math.round(newRating * 10) / 10; // 保留一位小数
        maintainer.completedOrders = completedCount;
        await maintainer.save();
      }
    }

    await order.populate(['userId', 'maintainerId']);

    res.status(200).json({
      success: true,
      message: '评价提交成功',
      code: 200,
      data: order
    });
  })
);

// 删除工单（仅管理员）
router.delete('/:orderId', 
  authenticate,
  authorize('admin'),
  asyncHandler(async (req, res) => {
    const { orderId } = req.params;

    const order = await Order.findById(orderId);
    if (!order) {
      return res.status(404).json({
        success: false,
        message: '工单不存在',
        code: 404,
        data: null
      });
    }

    // 只能删除已取消或已完成的工单
    if (!['cancelled', 'evaluated'].includes(order.status)) {
      return res.status(400).json({
        success: false,
        message: '只能删除已取消或已评价的工单',
        code: 400,
        data: null
      });
    }

    await Order.findByIdAndDelete(orderId);

    res.status(200).json({
      success: true,
      message: '工单删除成功',
      code: 200,
      data: null
    });
  })
);

module.exports = router;